package com.baselib;
import java.net.*;
import java.io.*;
public class ConnectSocket {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws IOException {
		String host="10.223.88.7";
		//host = "60.247.106.211";
		int port = 4001;
		//port = 9999;
		String query = "<index_query>levellist~1	flag~0on1off</index_query><index_sortby>weight</index_sortby><index_orderby>0</index_orderby><index_pageno>1</index_pageno><index_pagesize>10</index_pagesize>";
		int len = query.length();
		query = "00000"+len+query;
		System.out.println(len);

		ConnectSocket cs = new ConnectSocket();
		String r = cs.Connect(host, port, query);
		System.out.println(r);
	
	}
	
	public String Connect(String host,int port,String query) throws IOException{
		
		Socket socket = new Socket(host, port);
		
		//Send message to socket server
		OutputStream os = socket.getOutputStream();		
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));		
		bw.write(query);
		bw.flush();
		
		//Read message from socket server
		InputStream is = socket.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		StringBuffer sb = new StringBuffer();
		int c;		
		while((c=br.read())!=-1){			
			sb.append((char)c);
		}
		return sb.toString();
			
		
	}
	
	public void TestConnect(){
		String host = "10.223.88.7";
		int port = 4001;
		
		try{
			System.out.println("runing");
			Socket socket = new Socket(host,port);
			OutputStream os = socket.getOutputStream();
			InputStream is = socket.getInputStream();
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
			String line = "flag~0on1off	levellist~1";
			bw.write(line);
			bw.flush();
			System.out.println("Send");			
			
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			StringBuffer sb = new StringBuffer();
		
			int c;
			char[] buf=new char[10];
		
			System.out.println(br.read(buf,0,10));
			
			System.out.println("back"+sb.toString());
			//BufferedReader sin = new BufferedReader();
			//PrintWriter os = new PrintWriter(socket.getOutputStream());
			
			//BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			br.close();
			bw.close();
			os.close();
			socket.close();
			System.out.println("finished");
		}catch(Exception e){
			
			System.out.println(e.toString());
		}

	}

}
